#include"DList.h"


DListNode* BuyDListNode(DLTDataType x)
{
	DListNode* newnode = (DListNode*)malloc(sizeof(DListNode));
	if (newnode == NULL)
	{
		perror("BuyDListNode->malloc failed");
		exit(-1);
	}
	newnode->next = NULL;
	newnode->prev = NULL;
	newnode->data = x;
	return newnode;
}

void DListPushBack(DListNode* phead, DLTDataType x)
{
	assert(phead);
	DListNode* newnode = BuyDListNode(x);
	DListNode* tail = phead->prev;
	phead->prev = newnode;
	newnode->next = phead;
	tail->next = newnode;
	newnode->prev = tail;
}

DListNode* DListInit()
{
	DListNode* phead = BuyDListNode(-1);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}


void DListPrint(DListNode* phead)
{
	assert(phead);
	DListNode* cur = phead->next;
	printf("head<=>");
	while (cur != phead)
	{
		printf("%d<=>", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

void DListPopBack(DListNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	DListNode* del = phead->prev;
	DListNode* tail = del->prev;
	tail->next = phead;
	phead->prev = tail;
	free(del); 
}

void DListPushFront(DListNode* phead, DLTDataType x)
{
	assert(phead);
	DListNode* newnode = BuyDListNode(x);
	newnode->next = phead->next;
	phead->next->prev = newnode;
	phead->next = newnode;
	newnode->prev = phead;
}

void DListPopFront(DListNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	DListNode* first = phead->next;
	DListNode* firstNext = first->next;
	phead->next = firstNext;
	firstNext->prev = phead;
	free(first);
}

int DListSize(DListNode* phead)
{
	int count = 0;
	DListNode* cur = phead->next;
	while (cur != phead)
	{
		count++;
		cur = cur->next;
	}
	return count;
}

void DListInsert(DListNode* pos, DLTDataType x)
{
	assert(pos);
	DListNode* newnode = BuyDListNode(x);
	DListNode* posPrev = pos->prev;
	newnode->next = pos;
	pos->prev = newnode;
	posPrev->next = newnode;
	newnode->prev = posPrev;
}

void DListEraser(DListNode* pos)
{
	assert(pos);
	DListNode* posPrev = pos->prev;
	DListNode* posNext = pos->next;
	free(pos);
	posPrev->next = posNext;
	posNext->prev = posPrev;
}


DListNode* DListFind(DListNode* phead, DLTDataType x)
{
	assert(phead);
	assert(phead->next != phead);
	DListNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void DListDestroy(DListNode* phead)
{
	assert(phead);
	DListNode* cur = phead->next;
	while (cur->next != phead)
	{
		DListNode* del = cur;
		cur = cur->next;
		free(del);
	}
	free(phead);
}













